package tts.controller.groups;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.GroupsHome;
import tts.dao.UsersHome;
import tts.model.Groups;
import tts.model.Users;

public class Insert extends RedirectAction {

	//fields
	private static final long serialVersionUID = -9037931792240948793L;
	@Autowired
	private GroupsHome groupsHome;
	@Autowired
	private UsersHome usersHome;
	private Groups groupIns;
	private ArrayList<String> strings;


	//get & set	
	public Groups getGroupIns() {
		return groupIns;
	}
	public void setGroupIns(Groups groupIns) {
		this.groupIns = groupIns;
	}
	public ArrayList<String> getStrings() {
		return strings;
	}
	public void setStrings(ArrayList<String> strings) {
		this.strings = strings;
	}

	//methods
	public String insert() {
		try {
			groupsHome.insert(this.groupIns);
			for (String s : strings) {
				Users user = usersHome.findByUsername(s);
				this.groupIns.getUsersList().add(user);
				user.getGroupsList().add(this.groupIns);
			}
		} catch (RuntimeException e) {
			if (e.getCause().getCause().getMessage().startsWith("Duplicate"))
				addFieldError("groupIns.groupName", getText("val.duplicate.group"));
			else addActionError(e.getMessage());
			return ERROR;
		}
		addActionMessage(getText("group.inserted"));
		return SUCCESS;
	}
}